<template>
  <div>
    <!-- 2.卡片视图 -->
    <el-card>

      <el-form :inline="true"  label-width="80px" style="margin-bottom: -15px">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="用户名">
              <el-input
                v-model="queryInfo.username"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="邮箱">
              <el-input
                v-model="queryInfo.email"
                placeholder="请输入邮箱"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="电话">
              <el-input
                v-model="queryInfo.phone"
                placeholder="请输入电话"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="9">
            <el-form-item>
              <el-button type="primary" @click="getUserListData" icon="el-icon-search">
                查询
              </el-button>
              <el-button type="primary" @click="resetQueryInfo" icon="el-icon-refresh-right">
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-left: 5px;">

          <el-form-item>
            <el-button type="primary" @click="addUserBack" icon="el-icon-plus">
              添加用户
            </el-button>
            <el-button type="primary" @click="removeUserById(multipleSelection)" icon="el-icon-delete">
              批量删除
            </el-button>

          </el-form-item>
        </el-row>

        <div class="informationBar">
          <span>已选择<span style="color: #1890ff;margin: 0 3px">{{multipleSelection.length}}</span>项</span>
          <span style="margin-left: 20px;color: #40a9ff"  @click="toggleSelection()">清空</span>
        </div>

      </el-form>

      <!-- 表格 -->
      <el-table
        ref="multipleTable"
        :data="userBackListData"
        tooltip-effect="dark"
        style="width: 100%;"
        @selection-change="handleSelectionChange">
        <el-table-column
          align="center"
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column type="index" label="序号" width="60"></el-table-column>

        <el-table-column
          align="center"
          prop="avatar"
          label="头像"
          width="140">
          <template slot-scope="scope">
            <el-avatar shape="square" size="small" :src="scope.row.avatar"></el-avatar>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="用户名"
          prop="username"
          width="140">
        </el-table-column>

        <el-table-column
          align="center"
          label="昵称"
          prop="nickName"
          width="140">
        </el-table-column>

        <el-table-column
          align="center"
          label="电话"
          prop="phone"
          width="180">
        </el-table-column>

        <el-table-column
          align="center"
          label="是否禁用"
          prop="enabled"
          width="140">
          <template slot-scope="scope">
            <el-switch
              disabled
              v-model="scope.row.enabled">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="是否为管理员"
          prop="isAdmin"
          width="140">
          <template slot-scope="scope">
            <el-switch
              disabled
              v-model="scope.row.isAdmin">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="创建日期"
          prop="createTime"
          width="180">
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDrawer(scope.row.id)"
            >编辑
            </el-button>

            <el-dropdown style="margin-left: 10px" size="mini" split-button type="primary">
              更多
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <span @click="showUserDetails(scope.row.id)">详情</span>
                </el-dropdown-item>
                <el-dropdown-item>
                  <span @click="isDialogFormVisible(scope.row.id)">密码</span>
                </el-dropdown-item>

                <el-dropdown-item>
                  <span @click="removeUserById([scope.row.id])">删除</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

            <!-- {{scope.row}} -->
          </template>
        </el-table-column>

      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-size="queryInfo.pagesize"
        :page-sizes="[5, 10, 20, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>


    </el-card>



    <!-- 编辑框 -->
    <el-drawer
      :title="drawerField.subtitle"
      :visible.sync="drawer"
      :with-header="false"
      size="35%">

      <div class="demo-drawer__content">

        <div style="text-align: center">
          <h2>{{drawerField.title}}</h2>
        </div>
        <el-divider></el-divider>

        <el-form :disabled="isDisabled" :model="userBackForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userBackForm.username"></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="nickName">
            <el-input v-model="userBackForm.nickName"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="userBackForm.sex">
              <el-radio label="男"></el-radio>
              <el-radio label="女"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否为管理员" prop="isAdmin">
            <el-switch
              v-model="userBackForm.isAdmin">
            </el-switch>
          </el-form-item>
          <el-form-item label="是否禁用" prop="enabled">
            <el-switch
              v-model="userBackForm.enabled">
            </el-switch>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userBackForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="userBackForm.phone"></el-input>
          </el-form-item>

          <el-form-item v-if="drawerField.isButton">
            <el-button @click="drawer = false" style="margin-right: 20px;">取消</el-button>
            <el-button type="primary" @click="submitForm">提交</el-button>
          </el-form-item>
        </el-form>

      </div>

    </el-drawer>

    <!-- 更改密码框 -->
    <el-dialog title="重新设定密码" :visible.sync="dialogFormVisible">
      <el-form :model="userBackForm">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input disabled v-model="userBackForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码" :label-width="formLabelWidth">
          <el-input v-model="userBackForm.password" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="resetPassword()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加框 -->
    <el-dialog title="添加用户" :visible.sync="dialogUserFormVisible">
      <el-form :model="userBackForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userBackForm.username"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="userBackForm.nickName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userBackForm.password"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userBackForm.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否为管理员" prop="isAdmin">
          <el-switch
            v-model="userBackForm.isAdmin">
          </el-switch>
        </el-form-item>
        <el-form-item label="是否禁用" prop="enabled">
          <el-switch
            v-model="userBackForm.enabled">
          </el-switch>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userBackForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userBackForm.phone"></el-input>
        </el-form-item>

        <el-form-item label="头像" prop="avatar">
          <el-input v-model="userBackForm.avatar"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUserFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUserForm">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>
<script>
import userBack from '@/api/userBack'

export default {
  name: 'User',
  data() {
    return {
      //封装的查询参数
      queryInfo: {
        username: '',
        email: '',
        phone: '',
        pageNum: 1,
        pageSize: 10,
      },

      //总记录数
      total: 0,

      //用户列表
      userBackListData: [],

      //已选择用户
      multipleSelection: [],

      //编辑框显示
      drawer: false,

      //用户表单
      userBackForm: {},
      //校验规则
      rules: {
        username: [
          {required: true, message: '请输入用户姓名', trigger: 'blur'},
          {min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur'}
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
      },

      //角色列表选项
      roleOptions: [],
      //用户角色
      userRole: [],

      dialogFormVisible: false,
      formLabelWidth: '120px',

      //添加用户显示框
      dialogUserFormVisible: false,

      isDisabled: false,
      drawerField: {
        subtitle: '',
        title: '',
        isButton: false
      }

    }
  },
  created() {
    this.getUserListData()
    //this.getAllRoles()
  },
  methods: {
    //清空选择
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },

    //已经选中的列表
    handleSelectionChange(val) {
      this.multipleSelection = val.map((x) => {
        return x.id;
      });
    },


    //展开编辑抽屉
    showEditDrawer(id){
      this.drawerField.subtitle = '编辑框'
      this.drawerField.isButton = true
      this.drawerField.title = '编辑'

      this.isDisabled = false
      this.drawer = true
      // this.getUserRoles(id)
      this.getUserById(id)
    },

    //展开详情抽屉
    showUserDetails(id){
      this.drawerField.subtitle = '详情框'
      this.drawerField.isButton = false
      this.drawerField.title = '用户详情'

      this.isDisabled = true
      this.drawer = true
      // this.getUserRoles(id)
      this.getUserById(id)
    },

    //提交用户表单，修改用户信息
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.updateUserById()
        } else {
          return false
        }
      });
    },

    //获取用户列表
    getUserListData() {
      userBack.getPageList(this.queryInfo).then(res => {
        this.userBackListData = res.data.records
        this.total = res.data.total
      })
    },

    //分页
    handleSizeChange(val) {
      this.queryInfo.pageSize = val;
      this.getUserListData();
    },
    handleCurrentChange(val) {
      this.queryInfo.pageNum = val; // 获取新页码
      this.getUserListData();
    },

    //查询用户
    getUserById(id){
      userBack.getUserById(id).then(res => {
        this.userBackForm = res.data
      })
    },

    //更新用户
    updateUserById(){
      userBack.updateUserById(this.userBackForm).then(res => {
        this.drawer = false
        this.getUserListData()
      })
    },

    //重置查询信息
    resetQueryInfo(){
      this.queryInfo.username = ''
      this.queryInfo.email = ''
      this.queryInfo.phone = ''
    },

    // //获取用户角色列表
    // async getUserRoles(id){
    //   const { data: res } = await this.$http.get(
    //     `/userRole/userRole/${id}`,
    //   );
    //   if (res.code !== 200) {
    //     return this.$message.error("更新用户信息失败！,错误信息为：" + res.msg);
    //   }
    //   this.userRole = res.data
    //
    // },
    //
    // //获取所有用户列表
    // async getAllRoles(){
    //   this.roleOptions.length = 0
    //   const { data: res } = await this.$http.get(
    //     "/role/allRoles",
    //   );
    //
    //   if (res.code !== 200) {
    //     return this.$message.error("更新用户信息失败！,错误信息为：" + res.msg);
    //   }
    //   this.roleOptions = res.data
    // },

    //删除用户
    removeUserById(ids){
      if (ids.length === 0) return this.$message.error("请先选择至少一条");

      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          userBack.deleteUserById(ids).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getUserListData()
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    isDialogFormVisible(id){
      this.getUserById(id)
      this.dialogFormVisible = true
    },

    //重置密码
    resetPassword(){
      this.updateUserById()
      this.dialogFormVisible = false
      this.$message({
        message: '修改成功',
        type: 'success'
      });
    },

    //添加用户
    addUserBack(){
      this.dialogUserFormVisible = true
    },

    //提交添加用户表单
    submitUserForm(){
      userBack.addUserBack(this.userBackForm).then(res => {
        this.dialogUserFormVisible = false
        this.$message({
          message: '添加成功',
          type: 'success'
        });
        this.getUserListData()
      })
    }
  }

}
</script>
<style scoped>

.informationBar{
  height: 45px;
  line-height: 45px;
  padding-left: 45px;
  background-color: #e6f7ff;
  border: 1px solid #8bd3ff;
  border-radius: 5px;
  margin-bottom: 20px;
}

</style>
